package com.cirkana.viewer.security;

import java.io.DataInputStream;
import java.io.DataOutputStream;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.cirkana.CirkanaException;
import com.cirkana.DataResolverUtil;
import com.cirkana.PassData;
import com.cirkana.ViewerActivity;
import com.cirkana.data.DataNotFoundException;
import com.cirkana.serial.bin.BinarySerializationException;
import com.cirkana.serial.bin.BinarySerializationUtil;
import com.cirkana.viewer.R;
import com.cirkana.viewer.data.security.User;

public class SignInActivity extends ViewerActivity {

	private Button signinButton;
	private EditText userEditText;
	private EditText passwordEditText;

	private SignInPassData passData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signin);

		this.signinButton = ((Button) findViewById(R.id.login_signin));
		this.userEditText = ((EditText) findViewById(R.id.user));
		this.passwordEditText = ((EditText) findViewById(R.id.password));

		this.passData = (SignInPassData) getRequest(SignInPassData.class);
		if (this.passData.hasProfile()) {
			this.userEditText.setText(this.passData.getUser().getNickName());
		}

		this.signinButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String userName = userEditText.getText().toString();
				String userPassword = passwordEditText.getText().toString();
				try {
					User user = (User) DataResolverUtil.getSecurityDataResolver().getUser(userName, userPassword);
					SignInPassData result = new SignInPassData();
					result.setUser(user);
					setResponse(RESULT_OK, result);
					finish();
				} catch (DataNotFoundException e) {
					showErrorMessage(getLiteral(R.string.sing_in), getLiteral(R.string.error_invalid_login));
				} catch (CirkanaException e) {
					showErrorMessage(e);
				}
			}
		});

	}

	public static class SignInPassData extends PassData {

		private User user;

		public boolean hasProfile() {
			return this.user != null;
		}

		public User getUser() {
			return user;
		}

		public void setUser(User user) {
			this.user = user;
		}

		public SignInPassData() {
		}

		public SignInPassData(User user) {
			this.user = user;
		}

		@Override
		public void serialize(DataOutputStream out) throws BinarySerializationException {
			BinarySerializationUtil.serializeSerializable(this.user, out);
		}

		@Override
		public void deserialize(DataInputStream in) throws BinarySerializationException {
			this.user = (User) BinarySerializationUtil.deserializeSerializable(User.class, in);
		}

		@Override
		public String toString() {
			StringBuilder s = new StringBuilder("{");

			s.append("profile=");
			if (this.user == null)
				s.append("(null)");
			else
				s.append(this.user.toString());

			s.append("}");
			return s.toString();
		}
	}

}
